package com.thread.threadfirst.javaBase.classLoader;

import java.io.*;

/**
 * 自定义类加载器
 */
public class CustomClassLoader extends ClassLoader {

    private String fileSuffix=".class";
    private String classLoaderName;
    private String loadPath;

    public CustomClassLoader(ClassLoader parent,String classLoaderName) {
        //指定当前类加载器的父类加载类
        super(parent);
        this.classLoaderName = classLoaderName;
    }

    public CustomClassLoader(String classLoaderName) {
        //使用默认的AppClassLoader 应用类加载器 作为本类的父类加载器
        super();
        this.classLoaderName = classLoaderName;
    }

    public void setLoadPath(String loadPath) {
        this.loadPath = loadPath;
    }

    private byte[] loadClassData(String name){
        byte[] data = null;
        ByteArrayOutputStream baos = null;
        InputStream is=null;

        try {
            name =name.replace(".","\\");
            String fileName=loadPath+name+fileSuffix;
            File file=new File(fileName);
            is=new FileInputStream(file);
            baos=new ByteArrayOutputStream();
            int ch;
            while (-1 != (ch=is.read())){
                baos.write(ch);
            }
            data=baos.toByteArray();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (baos!=null) {
                try {
                    baos.close();

                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }

    public Class<?> findClass(String name){
        byte[] bytes = loadClassData(name);
        return defineClass(name,bytes,0,bytes.length);
    }
}
